import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class Text_DataSource {
    public static void main(String[] args) {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java113?characterEncodin" +
                "g=utf8&allowPublicKeyRetrieval=true&useSSL=false");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");

        DataSource dataSource = mysqlDataSource;

        Connection connection = null;
        // 会进行一次预编译
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 获取数据库连接
            connection = dataSource.getConnection();
            // 设置查询语句
            String sql = "select student_id, sn, name, mail, class_id from student where name = ?";
            preparedStatement = connection.prepareStatement(sql);
            // 获取要查询的人
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入要查询的姓名");
            String name = sc.next();
            // 用真实的值进行替换
            preparedStatement.setString(1,name);
            // 执行SQL语句，获取结果集
            resultSet = preparedStatement.executeQuery();
            // 获取学生信息
            while (resultSet.next()){
                long id = resultSet.getLong(1);
                String sn = resultSet.getString(2);
                String sName = resultSet.getString(3);
                String mail = resultSet.getString(4);
                long cId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0},学生学号={1},学生姓名={2},学生邮箱={3},班级名={4}",id,sn,sName,mail,cId));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
